<template>
  <div>
    <el-card>
      <!-- 列表区 -->
      <div style="height: 60vh">
        <el-skeleton :loading="loading" animated>
          <el-table :data="paginatedData" border height="100%" style="width: 100%; margin-top:20px">
            <el-table-column prop="sensorName" label="传感器名称" />
            <el-table-column prop="sensorModel" label="传感器型号" />
            <el-table-column prop="counts" label="数量" />
            <el-table-column prop="sensorDesc" label="监测内容" />
          </el-table>
        </el-skeleton>
      </div>
      <!-- 分页 -->
      <template #footer>
        <div style="margin-top: -30px">
          <Pagination
              :total="total"
              :current-page.sync="searchForm.current"
              :total-pages="totalPages"
              @update:currentPage="handlePageChange"
          />
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref, watch} from "vue";
import { useRouter } from 'vue-router'
import siApi from '@/api/sensorInfo'
import Pagination from '@/components/Table/Pagination'
import { ElMessage } from 'element-plus';
import axios from "axios";

const router = useRouter();
// Dom 挂载之后
onMounted(() => {
  getSensorTableData();
})
//数据
const allTableData = ref([]);//接收后端全部结果
const tableData = ref([]);
const total = computed(() => tableData.value.length);//总记录条数
const totalPages = ref(1);//总页数
// 监听 allTableData 的变化，并同步更新 tableData
watch(allTableData, (newData) => {
  tableData.value = [...newData];
});

watch(total, (newData) => {
  totalPages.value = Math.ceil(newData / searchForm.size);
})

const handlePageChange = (page) => {
  searchForm.current = page;
};

//搜索条件
const searchForm = reactive({
  current: 1,
  size: 11,
})

// 获取传感器信息列表
const getSensorTableData = async () => {
  //分页条件查询
  // const res = await siApi.getFaultDiagnosesData({size: searchForm.size, current: searchForm.current});
  const res = await siApi.getSensorData({size: null, current: null});//查询全部
  if (res.data.status) {
    //用all前缀来接收保存
    allTableData.value = res.data.data;
  } else {
    ElMessage.error("获取后端数据失败");
    console.log(res.data.message);
  }
}

//分页监听
// 计算当前页需要显示的数据
const paginatedData = computed(() => {
  const start = (searchForm.current - 1) * searchForm.size;
  const end = start + searchForm.size;
  return tableData.value.slice(start, end);
});

//加载loading页面
const loading = ref(true);
watch(
    () => paginatedData.value,
    (newValue) => {
      loading.value = !(newValue && newValue.length > 0);
    },
    //配置项确保在组件挂载时，立即执行一次回调，以根据初始值正确设置 loading 的状态
    { immediate: true } // 立即执行一次，以确保初始值状态正确
);
</script>

<style scoped lang="scss">
/*card背景、边框*/
.el-card {
  background-color: transparent;
  --el-card-border-color: transparent;
}
/*数据表背景*/
.el-table {
  background-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-header-bg-color: transparent;
}
</style>